package cn.net.sinodata.common.core.utils;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.function.Supplier;

public class TransactionUtil {

    /**
     * 执行一个无返回值事务
     */
    public static void executeWithoutResult(Runnable runnable) {
        PlatformTransactionManager txManager = SpringUtils.getBean(PlatformTransactionManager.class);
        TransactionDefinition def = SpringUtils.getBean(TransactionDefinition.class);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            runnable.run();
            txManager.commit(status);
        } catch (Throwable t) {
            txManager.rollback(status);
            throw t;
        }
    }

    /**
     * 执行一个有返回值的事务
     */
    public static <T> T executeWithResult(Supplier<T> supplier) {
        PlatformTransactionManager txManager = SpringUtils.getBean(PlatformTransactionManager.class);
        TransactionDefinition def = SpringUtils.getBean(TransactionDefinition.class);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            T result = supplier.get();
            txManager.commit(status);
            return result;
        } catch (Throwable t) {
            txManager.rollback(status);
            throw t;
        }
    }

    /**
     * 自定义事务属性（可选）
     */
    public static <T> T execute(TransactionDefinition definition, Supplier<T> supplier) {
        PlatformTransactionManager txManager = SpringUtils.getBean(PlatformTransactionManager.class);
        TransactionStatus status = txManager.getTransaction(definition);
        try {
            T result = supplier.get();
            txManager.commit(status);
            return result;
        } catch (Throwable t) {
            txManager.rollback(status);
            throw t;
        }
    }
}
